package com.alipay.rebate.shop.filter;

import com.alipay.rebate.shop.utils.MDCUtil;
import com.alipay.rebate.shop.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

/**
 * 初始化log
 */
public class LogFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(LogFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.debug("LogFilter init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        logger.debug("LogFilter doFilter");
        logInit(servletRequest);
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        logger.debug("LogFilter destroy");
    }

    public void logInit(ServletRequest servletRequest){
        HttpServletRequest request =(HttpServletRequest) servletRequest;
        String uri = request.getRequestURI();
        String contextPath = request.getContextPath();
        String queryString = request.getQueryString();
        String remoteUser = request.getRemoteUser();
        String requestUrl = request.getRequestURL().toString();
        String remoteAddr = request.getRemoteAddr();
        String remoteHost = request.getRemoteHost();
        String remotePort = request.getRemoteHost();
        logger.debug("request uri is : {}",uri);
        logger.debug("context path is : {}",contextPath);
        logger.debug("queryString is : {}",queryString);
        logger.debug("remoteUser is : {}",remoteUser);
        logger.debug("request url is : {}",requestUrl);
        logger.debug("remote addr is : {}",remoteAddr);
        logger.debug("remote host is : {}",remoteHost);
        logger.debug("remote port is : {}",remotePort);
        MDCUtil.putAction(uri);
        MDCUtil.putDestination("localhost");
        MDCUtil.putRequestAddr(remoteAddr);
        MDCUtil.putRequestTime(new Date());

        HttpSession httpSession = request.getSession();
        User adminUser = (User) httpSession.getAttribute("adminUser");
//        MDCHelper.putUserId(adminUser.getUserId());
    }
}
